package com.example.actordemo1.routering;

import akka.actor.*;
import akka.japi.Function;
import akka.japi.pf.DeciderBuilder;
import akka.routing.FromConfig;
import akka.routing.RoundRobinPool;

import java.io.IOException;
import java.time.Duration;

/**
 * 路由actor
 */
public class MasterRouterActor extends AbstractActor {

//    private  final SupervisorStrategy strategy = new OneForOneStrategy(3, Duration.ofMinutes(1),
//            new Function<Throwable, SupervisorStrategy.Directive>() {
//                @Override
//                public SupervisorStrategy.Directive apply(Throwable t){
//                    if(t instanceof  Exception){
//                       return   SupervisorStrategy.resume();
//                    }else {
//                        return SupervisorStrategy.restart();
//                    }
//
//
//                }
//            });
private  final SupervisorStrategy strategy = null;
    ActorRef router = null;

    @Override
    public void preStart() throws Exception {
        //直接创建
//        router = getContext().actorOf(new RoundRobinPool(3)
//                .props(Props.create(RouterActor.class)),"taskActor");


        //配置 deployment 创建
        router =  getContext().actorOf(FromConfig.getInstance().withSupervisorStrategy(strategy)
                .props(Props.create(RouterActor.class)),"taskActor");

        System.out.println("router:"+router);
    }



    @Override
    public Receive createReceive() {
        return receiveBuilder().matchAny(o->{
            router.tell(o,getSender());
        }).build();
    }

    public static void main(String[] args) {
        ActorSystem actorSystem = ActorSystem.create("sys");
        ActorRef actorRef = actorSystem.actorOf(Props.create(MasterRouterActor.class), "masterRouterActor");
        actorRef.tell("helloA",ActorRef.noSender());
        actorRef.tell("hellob",ActorRef.noSender());
        actorRef.tell("helloc",ActorRef.noSender());
        actorRef.tell("helloe",ActorRef.noSender());
        actorRef.tell("hellof",ActorRef.noSender());
        actorRef.tell("hellog",ActorRef.noSender());
    }
}
